<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="账号类型">
        <el-radio-group v-model="userType" @input="typeChange">
          <el-radio :label="0">未注册</el-radio>
          <el-radio :label="1">已注册</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="userType == 0">
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model.trim="form.user_name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="user_password">
          <el-input
            v-model.trim="form.user_password"
            placeholder="密码长度为6-50位"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="user_password2">
          <el-input
            v-model.trim="form.user_password2"
            placeholder="请确认您的密码"
          />
        </el-form-item>
      </div>
      <div v-else-if="userType == 1">
        <el-form-item label="员工列表" prop="user_id">
          <el-select
            v-model="form.user_id"
            placeholder="请选择账号"
            @change="userChange"
          >
            <el-option
              v-for="item in userData"
              :key="item.id"
              :label="item.user_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="权限组" prop="role_id">
        <el-select
          v-model="form.role_id"
          placeholder="请选择权限组"
          @change="roleChange"
        >
          <el-option
            v-for="item in roleData"
            :key="item.id"
            :label="item.role_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <div v-if="userType == 0">
        <el-form-item label="手机号" prop="user_mobile">
          <el-input
            v-model.trim="form.user_mobile"
            maxlength="11"
            placeholder="用户手机号"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="user_email">
          <el-input v-model.trim="form.user_email" placeholder="修改用户邮箱" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="true_name">
          <el-input v-model.trim="form.true_name" placeholder="输入真实姓名" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department_id">
          <el-cascader
            v-model="form.department_id"
            clearable
            :options="treeData"
            placeholder="请选择部门"
            :props="defaultProps"
          />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { isPassword, isPhone } from '@/utils/validate'
import { getList as getDepList } from '@/api/organization'
import { getList as getGroupList } from '@/api/role'
import { queryList as getUserList } from '@/api/userManagement'
import { addAdmin, setAdmin } from '@/api/admin'
export default {
  name: 'MemberAdd',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!isPassword(value)) {
        callback(new Error(this.translateTitle('密码不能少于6位')))
      } else {
        callback()
      }
    }
    const validatePassword2 = (rule, value, callback) => {
      if (this.form.user_password != value) {
        callback(new Error(this.translateTitle('两次密码不一致')))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!isPhone(value)) {
        callback(new Error(this.translateTitle('请输入正确的手机号')))
      } else {
        callback()
      }
    }
    return {
      treeData: [],
      defaultProps: {
        children: 'sub_dep',
        label: 'dep_name',
        value: 'id',
        checkStrictly: true,
        emitPath: false,
      },
      roleData: [],
      form: {},
      rules: {
        user_name: [
          { required: true, trigger: 'blur', message: '请输入菜单标题' },
        ],
        user_id: [{ required: true, trigger: 'blur', message: '请选择账号' }],
        role_id: [{ required: true, trigger: 'blur', message: '请选择权限组' }],
        user_password: [
          { required: true, trigger: 'blur', message: '请输入6-50位的密码' },
          {
            validator: validatePassword,
            trigger: 'blur',
          },
        ],
        user_password2: [
          { required: true, trigger: 'blur', message: '请确认密码' },
          {
            validator: validatePassword2,
            trigger: 'blur',
          },
        ],
        user_mobile: [
          { required: true, trigger: 'blur', message: '请输入手机号' },
          {
            validator: validatePhone,
            trigger: 'blur',
          },
        ],
      },
      title: '添加',
      dialogFormVisible: false,
      userType: 0,
      userData: [],
    }
  },
  methods: {
    showEdit() {
      this.dialogFormVisible = true
      this.getRoleData()
      this.fetchData()
    },
    close() {
      this.dialogFormVisible = false
      this.$refs['form'].resetFields()
      this.form = this.$options.data().form
      this.userType = 0
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.userType == 0) {
            const { data } = await addAdmin(this.form)
            if (data.is_success) {
              this.$baseMessage(
                '添加成功',
                'success',
                'vab-hey-message-success'
              )
              this.$emit('fetch-data')
              this.close()
            }
          } else if (this.userType == 1) {
            const { data } = await setAdmin(this.form)
            if (data.is_success) {
              this.$baseMessage(
                '添加成功',
                'success',
                'vab-hey-message-success'
              )
            }
            this.$emit('fetch-data')
            this.close()
          }
        }
      })
    },
    roleChange(id) {
      this.form.role_id = id
      this.$forceUpdate()
    },
    userChange(id) {
      this.form.user_id = id
    },
    typeChange(id) {
      this.$refs['form'].resetFields()
      if (id == 1) {
        this.getUserData()
      }
    },
    handleNodeClick(node) {
      this.form.department_id = node.id
      this.form.dep_name = node.dep_name
      this.$forceUpdate()
    },
    async fetchData() {
      const data = await getDepList({})
      this.treeData = data.data.length > 0 ? data.data : []
    },
    async getRoleData() {
      const data = await getGroupList({ status: 1 })
      this.roleData = data.data.length > 0 ? data.data : []
    },
    async getUserData() {
      const data = await getUserList({})
      this.userData = data.data.length > 0 ? data.data : []
    },
  },
}
</script>
